package ui;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JPanel;

import sniff.pack.CommonPacket;
import ui.util.YPUIUtil;
import ui.widget.TitleRetractablePanel;
import ui.widget.TransparentPanel;
import ui.widget.TxtPanel;
import ui.widget.YPanel;
import util.ByteUtil;

public class ByteMsgPanel extends YPanel {
	private CommonPacket pack;
	private JPanel headerBytePanel;
	private JPanel dataBytePanel;
	private JPanel dataStringPanel;
	private final String space = " ";
	private TitleRetractablePanel headPanel;
	private TitleRetractablePanel dataPanel;

	public ByteMsgPanel() {
		headerBytePanel = new YPanel();
		dataBytePanel = new YPanel();
		dataStringPanel = new YPanel();
	}

	private void initDataBytePanel() {
		if (dataPanel == null) {
			dataPanel = new TitleRetractablePanel(this.getWidth() - 10, 30, "Data");
			JPanel p1 = new TransparentPanel();
			p1.setLayout(new BorderLayout());
			p1.add(dataBytePanel, BorderLayout.WEST);
			p1.add(dataStringPanel, BorderLayout.CENTER);
			dataPanel.setMainPanel(p1);
			add(dataPanel);
		}
		initBytePanel(dataBytePanel, pack.getData(), this.getWidth() / 2 + 35);
	}

	private void initHeaderBytePanel() {
		if (headPanel == null) {
			headPanel = new TitleRetractablePanel(this.getWidth() - 10, 30, "Header");
			headPanel.setMainPanel(headerBytePanel);
			add(headPanel);
		}
		initBytePanel(headerBytePanel, pack.getHead(), this.getWidth() - 20);
	}

	private void initBytePanel(JPanel panel, byte[] bytes, int w) {
		panel.removeAll();
		String s = "" + space;
		for (int i = 0; i < bytes.length; i++) {
			byte b = bytes[i];
			String str = ByteUtil.byteToHexString(b);
			s += str + space;
			if ((i+1) % 8 == 0) {
				s += space + space;
			}
			if ((i+1) % 16 == 0||i==bytes.length-1) {
				TxtPanel t = new TxtPanel(w, 30, s);
				t.setMaximumSize(new Dimension(YPUIUtil.getScreenWidth(), 30));
				panel.add(t);
				s = "" + space;
			}
		}
		panel.validate();
		panel.repaint();
		panel.revalidate();
	}

	private void initDataStringPanel() {
		dataStringPanel.removeAll();
		String s = new String(pack.getData());
		for (int i = 0; i < s.length(); i += 20) {
			int endIndex = i + 20;
			if (endIndex > s.length()) {
				endIndex = s.length();
			}
			String str = s.substring(i, endIndex);
			TxtPanel t = new TxtPanel(this.getWidth() / 2 - 40, 30, str);
			dataStringPanel.add(t);
		}
		dataStringPanel.validate();
		dataStringPanel.repaint();
		dataStringPanel.revalidate();
	}

	public CommonPacket getPack() {
		return pack;
	}

	public void setPack(CommonPacket pack) {
		this.pack = pack;
		initHeaderBytePanel();
		initDataStringPanel();
		initDataBytePanel();
		repaint();
		validate();
		revalidate();
	}

}
